package cn.christ.com.mobilesafe.service;


import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.IBinder;

import java.util.List;

import cn.christ.com.mobilesafe.engine.ProcessProvider;
import cn.christ.com.mobilesafe.modle.ProcessInfo;

/**
 * @author xiaozhao 监听屏幕的关闭和开启的服务
 */
public class ScreenService extends Service {

    private ScreenReceiver mReceiver;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mReceiver = new ScreenReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mReceiver, filter);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mReceiver != null) {
            unregisterReceiver(mReceiver);
        }
    }

    class ScreenReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // 当屏被锁的时候，清理进程
            cleanProcesses(context);
        }

        // 清理进程
        private void cleanProcesses(Context context) {
            List<ProcessInfo> allProcessInfos = null;
            try {
                allProcessInfos = ProcessProvider.getAllProcessInfos(context);
                for (ProcessInfo info : allProcessInfos) {
                    ProcessProvider.killBackGroundProcess(context, info.processName);
                }
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

    }
}
